package com.dongdongkeji.base.api;

import android.content.Context;

import com.dongdongkeji.base.constant.BaseApiConstants;
import com.dongdongkeji.base.exceptions.ApiException;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Author: ChenJing
 * Date: 2017-06-19 下午 3:55
 * Version: 1.0
 */

public abstract class BaseObserver<T> implements Observer<T> {

    protected Context context;
    protected CompositeDisposable disposables;

    public BaseObserver(Context context, CompositeDisposable disposables) {
        this.context = context;
        this.disposables = disposables;
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.disposables.add(d);
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException){
            onError(BaseApiConstants.NETWORK_ERROR);
        }else if (e instanceof IOException){
            onError(BaseApiConstants.CONNECT_TIMEOUT);
        }else if (e instanceof ApiException){
            // TODO: 2017/6/19 0019 处理公共错误码
            ApiException apiException = (ApiException) e;
            onError(apiException.getErrorCode());
        }
    }

    @Override
    public abstract void onNext(T t);

    public abstract void onError(int errorCode);
}
